package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("EventRestController")
public class EventRestController extends CmiEmaController {

	/**
	 * Create a new Event entity
	 * 
	 */
	@RequestMapping(value = "/newEvent", method = RequestMethod.POST)
	@ResponseBody
	public Object newEvent(@RequestBody Event event) {
		eventService.saveEvent(event);
		return JSONObject.parse(cmiPsonService.toJsonString(eventDAO.findEventByPrimaryKey(event.getId()), 2));
	}

	@RequestMapping(value = "/restNewEvent", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewEvent(@RequestBody String eventJson) {
		Event event = new Gson().fromJson(eventJson, Event.class);
		appendReferences(event);
		eventService.saveEvent(event);
		return JSONObject.parse(cmiPsonService.toJsonString(eventDAO.findEventByPrimaryKey(event.getId()), 2));
	}

	@RequestMapping(value = "/saveEvent", method = RequestMethod.PUT)
	@ResponseBody
	public Event saveEvent(@RequestBody Event event) {
		eventService.saveEvent(event);
		return eventDAO.findEventByPrimaryKey(event.getId());
	}

	@RequestMapping(value = "/restSaveEvent", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveEvent(@RequestBody String eventJson) {
		Event event = new Gson().fromJson(eventJson, Event.class);
		appendReferences(event);
		CmiPsonService cmiPsonService = new CmiPsonService();
		eventService.saveEvent(event);
		return JSONObject.parse(cmiPsonService.toJsonString(eventDAO.findEventByPrimaryKey(event.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteEvent/{eventId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteEvent(@PathVariable Integer eventId) {
		Event event = eventDAO.findEventByPrimaryKey(eventId);
		eventService.deleteEvent(event);
	}

	@RequestMapping(value = "/restConfirmDeleteEvents")
	@ResponseBody
	public Object restConfirmDeleteEvents(@RequestBody Set<Integer> deleteEventsIds) {
		Set<Event> deleteEvents = eventDAO.findEventsByIds(deleteEventsIds);
		Set<Event> referencedEvents = eventService.loadReferenceEvents(deleteEvents);
		deleteEvents.removeAll(referencedEvents);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedEvents);
		jsonObject.put("deleteEntitys", deleteEvents);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteEvents")
	@ResponseBody
	public Object restDeleteEvents(@RequestBody Set<Event> deleteEvents) {
		Iterator<Event> iterator = deleteEvents.iterator();
		while (iterator.hasNext()) {
			Event currentEvent = iterator.next();
			eventService.deleteEvent(currentEvent);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listEvents");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadEvent/{eventId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEvent(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventAddressBySourceAddress/{eventId}/addressBySourceAddress", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventAddressBySourceAddress(@PathVariable Integer eventId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getSourceAddress(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventAddressByDiscoveryAddress/{eventId}/addressByDiscoveryAddress", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventAddressByDiscoveryAddress(@PathVariable Integer eventId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getDiscoveryAddress(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventSubject/{eventId}/subject", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventSubject(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getSubject(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventUserByAuditor/{eventId}/userByAuditor", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventUserByAuditor(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getAuditor(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventUrl/{eventId}/url", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventUrl(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getUrl(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventUserByReportor/{eventId}/userByReportor", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventUserByReportor(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getReportor(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventEvent/{eventId}/event", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventEvent(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getParent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventFoodbatch/{eventId}/foodbatch", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventFoodbatch(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getFoodbatch(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadEventEvents/{eventId}/events/{relatedeventId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventEvents(@PathVariable Integer eventId, @PathVariable Integer relatedeventId,
			@RequestBody CmiPagination cmiPagination) {
		Event event = eventDAO.findEventByPrimaryKey(relatedeventId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(event, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventAdultertypes/{eventId}/adultertypes/{relatedadultertypeId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventAdultertypes(@PathVariable Integer eventId, @PathVariable Integer relatedadultertypeId,
			@RequestBody CmiPagination cmiPagination) {
		Adultertype adultertype = adultertypeDAO.findAdultertypeByPrimaryKey(relatedadultertypeId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(adultertype, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventDiscoverylinks/{eventId}/discoverylinks/{relateddiscoverylinkId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventDiscoverylinks(@PathVariable Integer eventId,
			@PathVariable Integer relateddiscoverylinkId, @RequestBody CmiPagination cmiPagination) {
		Discoverylink discoverylink = discoverylinkDAO.findDiscoverylinkByPrimaryKey(relateddiscoverylinkId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(discoverylink, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventLaws/{eventId}/laws/{relatedlawId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventLaws(@PathVariable Integer eventId, @PathVariable Integer relatedlawId,
			@RequestBody CmiPagination cmiPagination) {
		Law law = lawDAO.findLawByPrimaryKey(relatedlawId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(law, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventMotives/{eventId}/motives/{relatedmotiveId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventMotives(@PathVariable Integer eventId, @PathVariable Integer relatedmotiveId,
			@RequestBody CmiPagination cmiPagination) {
		Motive motive = motiveDAO.findMotiveByPrimaryKey(relatedmotiveId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(motive, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventEventadulterlinks/{eventId}/eventadulterlinks/{relatedeventadulterlinkId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventEventadulterlinks(@PathVariable Integer eventId,
			@PathVariable Integer relatedeventadulterlinkId, @RequestBody CmiPagination cmiPagination) {
		Eventadulterlink eventadulterlink = eventadulterlinkDAO
				.findEventadulterlinkByPrimaryKey(relatedeventadulterlinkId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(eventadulterlink, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventEventhazards/{eventId}/eventhazards/{relatedeventhazardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventEventhazards(@PathVariable Integer eventId, @PathVariable Integer relatedeventhazardId,
			@RequestBody CmiPagination cmiPagination) {
		Eventhazard eventhazard = eventhazardDAO.findEventhazardByPrimaryKey(relatedeventhazardId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(eventhazard, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventEventpunishs/{eventId}/eventpunishs/{relatedeventpunishId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventEventpunishs(@PathVariable Integer eventId, @PathVariable Integer relatedeventpunishId,
			@RequestBody CmiPagination cmiPagination) {
		Eventpunish eventpunish = eventpunishDAO.findEventpunishByPrimaryKey(relatedeventpunishId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(eventpunish, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventEventqualitytypes/{eventId}/eventqualitytypes/{relatedeventqualitytypeId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventEventqualitytypes(@PathVariable Integer eventId,
			@PathVariable Integer relatedeventqualitytypeId, @RequestBody CmiPagination cmiPagination) {
		Eventqualitytype eventqualitytype = eventqualitytypeDAO
				.findEventqualitytypeByPrimaryKey(relatedeventqualitytypeId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(eventqualitytype, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventEventquantitytypes/{eventId}/eventquantitytypes/{relatedeventquantitytypeId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventEventquantitytypes(@PathVariable Integer eventId,
			@PathVariable Integer relatedeventquantitytypeId, @RequestBody CmiPagination cmiPagination) {
		Eventquantitytype eventquantitytype = eventquantitytypeDAO
				.findEventquantitytypeByPrimaryKey(relatedeventquantitytypeId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(eventquantitytype, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventPictures/{eventId}/pictures/{relatedpictureId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventPictures(@PathVariable Integer eventId, @PathVariable Integer relatedpictureId,
			@RequestBody CmiPagination cmiPagination) {
		Picture picture = pictureDAO.findPictureByPrimaryKey(relatedpictureId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(picture, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadEventVideos/{eventId}/videos/{relatedvideoId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadEventVideos(@PathVariable Integer eventId, @PathVariable Integer relatedvideoId,
			@RequestBody CmiPagination cmiPagination) {
		Video video = videoDAO.findVideoByPrimaryKey(relatedvideoId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(video, 2, cmiPagination));
	}

	public void appendReferences(Event event) {

		Address sourceAddress = event.getSourceAddress();
		if (sourceAddress != null)
			event.setSourceAddress(addressService.findAddressByPrimaryKey(sourceAddress.getId()));

		Address discoveryAddress = event.getDiscoveryAddress();
		if (discoveryAddress != null)
			event.setDiscoveryAddress(addressService.findAddressByPrimaryKey(discoveryAddress.getId()));

		Subject subject = event.getSubject();
		if (subject != null)
			event.setSubject(subjectService.findSubjectByPrimaryKey(subject.getId()));

		User auditor = event.getAuditor();
		if (auditor != null)
			event.setAuditor(userService.findUserByPrimaryKey(auditor.getId()));

		Url url = event.getUrl();
		if (url != null)
			event.setUrl(urlService.findUrlByPrimaryKey(url.getId()));

		User reportor = event.getReportor();
		if (reportor != null)
			event.setReportor(userService.findUserByPrimaryKey(reportor.getId()));

		Event parent = event.getParent();
		if (parent != null)
			event.setParent(eventService.findEventByPrimaryKey(parent.getId()));

		Foodbatch foodbatch = event.getFoodbatch();
		if (foodbatch != null)
			event.setFoodbatch(foodbatchService.findFoodbatchByPrimaryKey(foodbatch.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Event> eventsForParent = new HashSet<>();
		for (Event event_Parent : event.getEventsForParent()) {
			eventsForParent.add(eventService.findEventByPrimaryKey(event_Parent.getId()));
		}
		event.setEventsForParent(eventsForParent);

		// 引用表是纯联系表的情况
		Set<Adultertype> adultertypesForEvent = new HashSet<>();
		for (Adultertype adultertypeForEvent : event.getAdultertypesForEvent()) {
			adultertypesForEvent.add(adultertypeService.findAdultertypeByPrimaryKey(adultertypeForEvent.getId()));
		}
		event.setAdultertypesForEvent(adultertypesForEvent);

		// 引用表是纯联系表的情况
		Set<Discoverylink> discoverylinksForEvent = new HashSet<>();
		for (Discoverylink discoverylinkForEvent : event.getDiscoverylinksForEvent()) {
			discoverylinksForEvent
					.add(discoverylinkService.findDiscoverylinkByPrimaryKey(discoverylinkForEvent.getId()));
		}
		event.setDiscoverylinksForEvent(discoverylinksForEvent);

		// 引用表是纯联系表的情况
		Set<Law> lawsForEvent = new HashSet<>();
		for (Law lawForEvent : event.getLawsForEvent()) {
			lawsForEvent.add(lawService.findLawByPrimaryKey(lawForEvent.getId()));
		}
		event.setLawsForEvent(lawsForEvent);

		// 引用表是纯联系表的情况
		Set<Motive> motivesForEvent = new HashSet<>();
		for (Motive motiveForEvent : event.getMotivesForEvent()) {
			motivesForEvent.add(motiveService.findMotiveByPrimaryKey(motiveForEvent.getId()));
		}
		event.setMotivesForEvent(motivesForEvent);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Eventadulterlink> eventadulterlinksForEvent = new HashSet<>();
		for (Eventadulterlink eventadulterlink_Event : event.getEventadulterlinksForEvent()) {
			eventadulterlinksForEvent
					.add(eventadulterlinkService.findEventadulterlinkByPrimaryKey(eventadulterlink_Event.getId()));
		}
		event.setEventadulterlinksForEvent(eventadulterlinksForEvent);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Eventhazard> eventhazardsForEvent = new HashSet<>();
		for (Eventhazard eventhazard_Event : event.getEventhazardsForEvent()) {
			eventhazardsForEvent.add(eventhazardService.findEventhazardByPrimaryKey(eventhazard_Event.getId()));
		}
		event.setEventhazardsForEvent(eventhazardsForEvent);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Eventpunish> eventpunishsForEvent = new HashSet<>();
		for (Eventpunish eventpunish_Event : event.getEventpunishsForEvent()) {
			eventpunishsForEvent.add(eventpunishService.findEventpunishByPrimaryKey(eventpunish_Event.getId()));
		}
		event.setEventpunishsForEvent(eventpunishsForEvent);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Eventqualitytype> eventqualitytypesForEvent = new HashSet<>();
		for (Eventqualitytype eventqualitytype_Event : event.getEventqualitytypesForEvent()) {
			eventqualitytypesForEvent
					.add(eventqualitytypeService.findEventqualitytypeByPrimaryKey(eventqualitytype_Event.getId()));
		}
		event.setEventqualitytypesForEvent(eventqualitytypesForEvent);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Eventquantitytype> eventquantitytypesForEvent = new HashSet<>();
		for (Eventquantitytype eventquantitytype_Event : event.getEventquantitytypesForEvent()) {
			eventquantitytypesForEvent
					.add(eventquantitytypeService.findEventquantitytypeByPrimaryKey(eventquantitytype_Event.getId()));
		}
		event.setEventquantitytypesForEvent(eventquantitytypesForEvent);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Picture> picturesForEvent = new HashSet<>();
		for (Picture picture_Event : event.getPicturesForEvent()) {
			picturesForEvent.add(pictureService.findPictureByPrimaryKey(picture_Event.getId()));
		}
		event.setPicturesForEvent(picturesForEvent);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Video> videosForEvent = new HashSet<>();
		for (Video video_Event : event.getVideosForEvent()) {
			videosForEvent.add(videoService.findVideoByPrimaryKey(video_Event.getId()));
		}
		event.setVideosForEvent(videosForEvent);
	}

	@RequestMapping(value = "/restGetEventAddressBySourceAddress/{eventId}/addressBySourceAddress", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventAddressBySourceAddress(@PathVariable Integer eventId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getSourceAddress(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventAddressByDiscoveryAddress/{eventId}/addressByDiscoveryAddress", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventAddressByDiscoveryAddress(@PathVariable Integer eventId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getDiscoveryAddress(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventSubject/{eventId}/subject", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventSubject(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getSubject(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventUserByAuditor/{eventId}/userByAuditor", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventUserByAuditor(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getAuditor(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventUrl/{eventId}/url", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventUrl(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getUrl(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventUserByReportor/{eventId}/userByReportor", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventUserByReportor(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getReportor(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventEvent/{eventId}/event", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventEvent(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getParent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventFoodbatch/{eventId}/foodbatch", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventFoodbatch(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getFoodbatch(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventEvents/{eventId}/events", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventEvents(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getEventsForParent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventAdultertypes/{eventId}/adultertypes", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventAdultertypes(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getAdultertypesForEvent(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventDiscoverylinks/{eventId}/discoverylinks", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventDiscoverylinks(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getDiscoverylinksForEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventLaws/{eventId}/laws", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventLaws(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getLawsForEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventMotives/{eventId}/motives", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventMotives(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getMotivesForEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventEventadulterlinks/{eventId}/eventadulterlinks", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventEventadulterlinks(@PathVariable Integer eventId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getEventadulterlinksForEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventEventhazards/{eventId}/eventhazards", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventEventhazards(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getEventhazardsForEvent(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventEventpunishs/{eventId}/eventpunishs", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventEventpunishs(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getEventpunishsForEvent(),
				2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventEventqualitytypes/{eventId}/eventqualitytypes", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventEventqualitytypes(@PathVariable Integer eventId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getEventqualitytypesForEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventEventquantitytypes/{eventId}/eventquantitytypes", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventEventquantitytypes(@PathVariable Integer eventId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getEventquantitytypesForEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventPictures/{eventId}/pictures", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventPictures(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getPicturesForEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetEventVideos/{eventId}/videos", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetEventVideos(@PathVariable Integer eventId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(eventDAO.findEventByPrimaryKey(eventId).getVideosForEvent(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListEvents", method = RequestMethod.GET)
	@ResponseBody
	public Object restListEvents() {
		return JSONObject.parse(cmiPsonService.toJsonString(eventService.loadEvents(), 2));
	}

	@RequestMapping(value = "/restListEventsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListEventsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = eventPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Event> events = eventDAO.findAllEvents(startResult, cmiPagination.getPaginationSize());
//		删除id是-2的无效j
		
		Event nonValidatEvent = eventDAO.findEventById(-2);
		events.remove(nonValidatEvent);
		
		String eventString = cmiPsonService.toPsonString(events, 2, cmiPagination);

		return JSONObject.parse(eventString);
	}

	@RequestMapping("/eventSelectBox")
	@ResponseBody
	public JSONObject eventSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Address":
				entitySet = addressService.loadAddresssByIdSet(searchValue);
				break;
			case "Subject":
				entitySet = subjectService.loadSubjectsByIdSet(searchValue);
				break;
			case "User":
				entitySet = userService.loadUsersByIdSet(searchValue);
				break;
			case "Url":
				entitySet = urlService.loadUrlsByIdSet(searchValue);
				break;
			case "Foodbatch":
				entitySet = foodbatchService.loadFoodbatchsByIdSet(searchValue);
				break;

			// 被引用键
			case "Event":
				entitySet = eventService.loadEventsByIdSet(searchValue);
				break;

			case "Adultertype":
				entitySet = adultertypeService.loadAdultertypesByIdSet(searchValue);
				break;

			case "Discoverylink":
				entitySet = discoverylinkService.loadDiscoverylinksByIdSet(searchValue);
				break;

			case "Law":
				entitySet = lawService.loadLawsByIdSet(searchValue);
				break;

			case "Motive":
				entitySet = motiveService.loadMotivesByIdSet(searchValue);
				break;
			case "Eventadulterlink":
				entitySet = eventadulterlinkService.loadEventadulterlinksByIdSet(searchValue);
				break;
			case "Eventhazard":
				entitySet = eventhazardService.loadEventhazardsByIdSet(searchValue);
				break;
			case "Eventpunish":
				entitySet = eventpunishService.loadEventpunishsByIdSet(searchValue);
				break;
			case "Eventqualitytype":
				entitySet = eventqualitytypeService.loadEventqualitytypesByIdSet(searchValue);
				break;
			case "Eventquantitytype":
				entitySet = eventquantitytypeService.loadEventquantitytypesByIdSet(searchValue);
				break;
			case "Picture":
				entitySet = pictureService.loadPicturesByIdSet(searchValue);
				break;
			case "Video":
				entitySet = videoService.loadVideosByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Address":
				entitySet = addressDAO.findAllAddresss((pageNumber - 1) * paginationSize, paginationSize);
				count = addressService.countAddresss();
				break;
			case "Subject":
				entitySet = subjectDAO.findAllSubjects((pageNumber - 1) * paginationSize, paginationSize);
				count = subjectService.countSubjects();
				break;
			case "User":
				entitySet = userDAO.findAllUsers((pageNumber - 1) * paginationSize, paginationSize);
				count = userService.countUsers();
				break;
			case "Url":
				entitySet = urlDAO.findAllUrls((pageNumber - 1) * paginationSize, paginationSize);
				count = urlService.countUrls();
				break;
			case "Foodbatch":
				entitySet = foodbatchDAO.findAllFoodbatchs((pageNumber - 1) * paginationSize, paginationSize);
				count = foodbatchService.countFoodbatchs();
				break;

			// 被引用键
			case "Event":
				entitySet = eventDAO.findAllEvents((pageNumber - 1) * paginationSize, paginationSize);
				count = eventService.countEvents();
				break;

			case "Adultertype":
				entitySet = adultertypeDAO.findAllAdultertypes((pageNumber - 1) * paginationSize, paginationSize);
				count = adultertypeService.countAdultertypes();
				break;

			case "Discoverylink":
				entitySet = discoverylinkDAO.findAllDiscoverylinks((pageNumber - 1) * paginationSize, paginationSize);
				count = discoverylinkService.countDiscoverylinks();
				break;

			case "Law":
				entitySet = lawDAO.findAllLaws((pageNumber - 1) * paginationSize, paginationSize);
				count = lawService.countLaws();
				break;

			case "Motive":
				entitySet = motiveDAO.findAllMotives((pageNumber - 1) * paginationSize, paginationSize);
				count = motiveService.countMotives();
				break;
			case "Eventadulterlink":
				entitySet = eventadulterlinkDAO.findAllEventadulterlinks((pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventadulterlinkService.countEventadulterlinks();
				break;
			case "Eventhazard":
				entitySet = eventhazardDAO.findAllEventhazards((pageNumber - 1) * paginationSize, paginationSize);
				count = eventhazardService.countEventhazards();
				break;
			case "Eventpunish":
				entitySet = eventpunishDAO.findAllEventpunishs((pageNumber - 1) * paginationSize, paginationSize);
				count = eventpunishService.countEventpunishs();
				break;
			case "Eventqualitytype":
				entitySet = eventqualitytypeDAO.findAllEventqualitytypes((pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventqualitytypeService.countEventqualitytypes();
				break;
			case "Eventquantitytype":
				entitySet = eventquantitytypeDAO.findAllEventquantitytypes((pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventquantitytypeService.countEventquantitytypes();
				break;
			case "Picture":
				entitySet = pictureDAO.findAllPictures((pageNumber - 1) * paginationSize, paginationSize);
				count = pictureService.countPictures();
				break;
			case "Video":
				entitySet = videoDAO.findAllVideos((pageNumber - 1) * paginationSize, paginationSize);
				count = videoService.countVideos();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Address":
				entitySet = addressDAO.findAddressByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = addressService.countAddresssByName(queryword);
				break;
			case "Subject":
				entitySet = subjectDAO.findSubjectByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = subjectService.countSubjectsByName(queryword);
				break;
			case "User":
				entitySet = userDAO.findUserByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = userService.countUsersByName(queryword);
				break;
			case "Url":
				entitySet = urlDAO.findUrlByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = urlService.countUrlsByName(queryword);
				break;
			case "Foodbatch":
				entitySet = foodbatchDAO.findFoodbatchByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodbatchService.countFoodbatchsByName(queryword);
				break;

			// 被引用键
			case "Event":
				entitySet = eventDAO.findEventByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventService.countEventsByName(queryword);
				break;

			case "Adultertype":
				entitySet = adultertypeDAO.findAdultertypeByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = adultertypeService.countAdultertypesByName(queryword);
				break;

			case "Discoverylink":
				entitySet = discoverylinkDAO.findDiscoverylinkByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = discoverylinkService.countDiscoverylinksByName(queryword);
				break;

			case "Law":
				entitySet = lawDAO.findLawByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = lawService.countLawsByName(queryword);
				break;

			case "Motive":
				entitySet = motiveDAO.findMotiveByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = motiveService.countMotivesByName(queryword);
				break;
			case "Eventadulterlink":
				entitySet = eventadulterlinkDAO.findEventadulterlinkByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = eventadulterlinkService.countEventadulterlinksByName(queryword);
				break;
			case "Eventhazard":
				entitySet = eventhazardDAO.findEventhazardByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventhazardService.countEventhazardsByName(queryword);
				break;
			case "Eventpunish":
				entitySet = eventpunishDAO.findEventpunishByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = eventpunishService.countEventpunishsByName(queryword);
				break;
			case "Eventqualitytype":
				entitySet = eventqualitytypeDAO.findEventqualitytypeByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = eventqualitytypeService.countEventqualitytypesByName(queryword);
				break;
			case "Eventquantitytype":
				entitySet = eventquantitytypeDAO.findEventquantitytypeByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = eventquantitytypeService.countEventquantitytypesByName(queryword);
				break;
			case "Picture":
				entitySet = pictureDAO.findPictureByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = pictureService.countPicturesByName(queryword);
				break;
			case "Video":
				entitySet = videoDAO.findVideoByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = videoService.countVideosByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
